<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/4
 * Time: 15:21
 * 考题
 */

namespace app\index\controller;


class Trainingquestions
{
    //考试记录
    const examinationrecord = [
        'userId'=>"",            //用户id  usermanage(id)
        'userName'=>'',          //用户名
        'examinationName'=>'',   //本次考试名称
        'datetime'=>'',          //考试时间
        'getScore'=>'0',         //考试得分
        'number'=>"0",           //考题数量
        "allScore"=>'0',         //考试总分
        "finish"=>false,         //是否完成考试
    ];

    //考试考题
    const examinationtopic = [
        'recordId'=>'',          //考试记录id
        'topic'=>'',             //题目
        'options'=>[],           //选项
        'result'=>'',            //真实答案
        'answer'=>'',            //答题答案
        'score'=>'',             //题目分数
    ];

    public static function getData($where, $one = true, $table = 'trainingquestions')
    {
        return ($one == true) ? getFirst(mongo($table)->where($where)->select()) : mongo($table)->where($where)->select();
    }
    public static function setData($where, $data, $table = 'trainingquestions')
    {
        mongo($table)->where($where)->update($data);
    }
    public static function insertData($data, $table = 'trainingquestions')
    {
        mongo($table)->insert($data);
        return mongo($table)->getLastInsID();
    }
    public static function deleteData($where, $table = 'trainingquestions')
    {
        mongo($table)->where($where)->delete();
    }

    /**
     *  发布考试
     *  @param string $id              试卷id
    @param array  $positionIds     职位id
    @param string $number          题目数量
    @param string $allScore        总分数
    @param string $examinationName 本次考试名称
     */
    public static function  publishExamination($id = '', $positionIds = [], $number = '', $allScore = '', $examinationName = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id          = input('id');
        $positionIds = input('positionIds/a', []);
        $number      = input('number');
        $allScore    = input('allScore');
        $examinationName = input('examinationName');

        $examinations = TrainingManage::getData(['paperId'=>$id], false);//所有考题

        if($number > count($examinations)) return RD(FAIL, '考试题目不够请录入考题');

        foreach ($positionIds as $positionId)
        {
            $result =  User::getData(['position_id'=>$positionId]);
            if(empty($result)) {continue;}

            $recordId = self::insertData(array_merge(self::examinationrecord, ['userId'=>$result['id'], 'userName'=>$result['username'],
                'examinationName'=>$examinationName, 'datetime'=>date('Y-m-d'), 'number'=>count($examinations), 'allScore'=>$allScore]));
            //插入考题
            $scoreindex = [];
            while(count($scoreindex) < $number) {  //考题数量
                $index = rand(0, count($examinations) - 1);

                if(!in_array($index, $scoreindex)) {
                    array_push($scoreindex, $index);
                    $examination = $examinations[$index];

                    $insertData = [
                        'recordId'  =>$recordId,                         //考试记录id
                        'topic'     =>$examination['topic'],             //题目
                        'options'   =>$examination['options'],           //选项
                        'result'    =>$examination['result'],            //真实答案
                        'answer'    =>'',                                //答题答案
                        'score'     =>($allScore / $number),             //题目分数
                    ];
                    self::insertData($insertData);//插入考题
                }
            }
        }
        return RD(SUCCESS);
    }

    /**
     * 根据日期获取所有考试
     * @param string $datetime     考试日期
     */
    public static function getExaminations($datetime = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $datetime = input('datetime');
        $pageSize = input('pageSize');
        $currentPage = input('currentPage');
        $where = [
            'userId' => cookie('userId'),
            'finish' => false,
            'datetime'=>['like', '.*'.$datetime.'.*'],
        ];
        $result = self::getData($where, false);
        $count = count($result);
        array_paging($result, ($currentPage - 1) * $pageSize, $pageSize);
        return RD(SUCCESS, ['total'=>$count, 'data'=>$result]);
    }
    /**
     * 根据日期获取所有考试历史
     * @param string $datetime     考试日期
     */
    public static function getHistoryExaminations($datetime = '', $keyword = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $datetime = input('datetime');
        $keyword  = input('keyword', '');
        $pageSize = input('pageSize');
        $currentPage = input('currentPage');
        $where = [
            'finish' => true,
            'datetime'=>['like', $datetime.'.*'],
            'userName|examinationName'=>['like', ".*".$keyword.'.*'],
        ];
        $result = self::getData($where, false);

        $count = count($result);
        array_paging($result, ($currentPage - 1) * $pageSize, $pageSize);
        return RD(SUCCESS, ['total'=>$count, 'data'=>$result]);
    }
    /**
     * 获取考试详细题目信息
     * @param string $id  考试id
     * @return array
     */
    public static function getExaminationTopics($id = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $id = input('id');
        $pageSize = input('pageSize');
        $currentPage = input('currentPage');
        $result = self::getData(['recordId'=>$id], false);
        $count = count($result);
        array_paging($result, ($currentPage - 1) * $pageSize, $pageSize);
        return RD(SUCCESS, ['total'=>$count, 'data'=>$result]);
    }
    /**
     * 回答题目
     * @param array $answers  回答答案
     */
    public static function answerExaminationTopic($answers = [])
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $answers = input('answers/a', []);
        foreach ($answers as $key=>$value) {
            self::setData(['id'=>$value['id']], ['answer'=>$value['answer']]);
        }

        $topicId  = $answers[0]['id'] ?? '';
        $recordId = self::getData(['id'=>$topicId])['recordId'] ?? '';
        $result   = self::getData(['recordId'=>$recordId], false);
        $allScore = 0;
        //得分
        foreach ($result as $key=>$value) {
            if($value['answer'] == $value['result']) {
                $allScore += $value['score'];
            }
        }
        self::setData(['id'=>$recordId], ['getScore'=>(string)$allScore, 'finish'=>true]);
        return RD(SUCCESS, (string)$allScore);
    }
}